from pyaudio import PyAudio,paInt16
import wave
import httplib2
import json
import base64
import gl
import threading
import time
from pkg.nlp import trans
import os
from pkg.driver import all_command


def save_wave_file(file_name,data):
    channels = 1
    frame_rate = 8000
    sample_width = 2
    wf=wave.open(file_name,'w')
    wf.setnchannels(channels)
    wf.setsampwidth(sample_width)
    wf.setframerate(frame_rate)
    wf.writeframes(data)
    wf.close()


def voice_2_text(file_name,tok):
    fp = open(file_name, 'rb')
    try:
        content = fp.read()
    except Exception as Err:
        fp.close()
        print(Err)
        return ''
    else:
        fp.close()
        lens = len(content)
    try:
        http = httplib2.Http(gl.g_http_catch_dir)
        data = {
            'format': 'wav',
            'rate': 8000,
            'channel': 1,
            'cuid': gl.get_mac_address(),
            'token': tok,
            'speech': base64.b64encode(content).decode(),
            'len': lens
        }
        data = json.dumps(data)
        res, content = http.request('http://vop.baidu.com/server_api', 'POST', data, {'Content-Type': 'application/json'})
        if res.status != 200:
            print('状态错误，错误码：' + str(res.status))
            return ''
        js_data = json.loads(content.decode())
        if js_data['err_no'] != 0:
            print('识别失败，错误信息:' + js_data['err_msg'])
            return ''
        return js_data['result']
    except Exception as Err:
        print(Err)
        return ''


def input_thread():
    channels = 1
    frame_rate = 8000
    num_samples = 2000
    while True:
        time.sleep(0.1)
        if(gl.g_is_recording):
            pa = PyAudio()
            my_buffer = bytes()
            file_name=gl.g_temp_dir+'/'+gl.get_temp_file_name('wav')
            stream = pa.open(format=paInt16, channels=channels, rate=frame_rate, input=True,
                             frames_per_buffer=num_samples)
            while(gl.g_is_recording):
                string_audio_data = stream.read(num_samples)
                my_buffer += string_audio_data
            save_wave_file(file_name, my_buffer)
            stream.close()
            txt=voice_2_text(file_name,gl.g_token)
            os.remove(file_name)
            if len(txt)==0:
                all_command.default_act('')
            else:
                t=threading.Thread(target=trans.translate,args=(txt,))
                t.start()


def voice_in_thread():
    t = threading.Thread(target=input_thread)
    t.start()